import json
import re

import jsonpath
import requests


def main():
    s = requests.Session()
    login_post_url = 'http://192.168.1.1/cgi-bin/luci'
    post_data = {
        'luci_username': 'root',
        'luci_password': 'admin',
    }

    headers = {'Cache-Control':'no-cache',
        'Connection':'keep-alive',
        'Content-Type':'application/x-www-form-urlencoded',
        'Host':'192.168.1.1',
        'Origin': 'http://192.168.1.1',
        'Pragma':'no-cache',
        'Referer': 'http://192.168.1.1/cgi-bin/luci',
        'Upgrade-Insecure-Requests':'1',
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.80 Safari/537.36',
    }
    response = s.post(url = login_post_url, data = post_data, headers = headers)

    print(response.url)


    response.encoding = 'utf-8'
    pattern = r'stok=(\w{32})'
    rr = re.compile(pattern)

    stok = rr.search(response.text)
    print(stok.group())


    get_url = login_post_url + '/;' + stok.group()
    response = s.get(url = get_url, params = {'status': '1'})
    s.close()
    response.encoding = 'utf-8'
    dates = json.loads(response.text)
    dates = dates['leases']
    print('当前在线主机{}台:'.format(len(dates)))
    for date in dates:
        print('{}\t{}\t{}'.format(date['ipaddr'],date['macaddr'],date['hostname']))

if __name__ == "__main__":
    main()
